package utils

import (
	"common"
	"encoding/binary"
	"encoding/json"
	"fmt"
	"net"
)

type Utils struct {
	Conn net.Conn
	Buf  [1024 * 4]byte
}


// ReadMes read message
func (this *Utils) ReadMes() (mes common.Message, err error) {
	// 读取 数据长度
	fmt.Println("start read mes....")
	n, err := this.Conn.Read(this.Buf[:4])
	if n != 4 || err != nil {
		fmt.Printf("read len(data) err, err=%v\n", err)
		return
	}
	mLen := binary.BigEndian.Uint32(this.Buf[:4])
	// 读取数据内容
	n, err = this.Conn.Read(this.Buf[:mLen])
	if n != int(mLen) || err != nil {
		fmt.Printf("read data err, err=%v\n", err)
		return
	}
	if err = json.Unmarshal(this.Buf[:n], &mes); err != nil {
		fmt.Println("read mes fail", err)
		return
	}
	fmt.Println("read success mes....")
	return
}

// WriteMes send message
func (this *Utils) WriteMes(mes *common.Message) (err error) {
	data, err := json.Marshal(mes)
	if err != nil {
		fmt.Println(err)
		return
	}

	mlen := uint32(len(data))
	binary.BigEndian.PutUint32(this.Buf[:4], mlen)
	// fmt.Printf("send len is %v, send data is %v\n", mlen, string(data))
	// 发送数据长度
	n, err := this.Conn.Write(this.Buf[:4])
	if n != 4 || err != nil {
		fmt.Printf("send len(data) err, err=%v\n", err)
		return
	}
	// 发送数据
	n, err = this.Conn.Write(data)
	if n != int(mlen) || err != nil {
		fmt.Printf("send data err, err=%v\n", err)
		return err
	}
	fmt.Println("send success")
	return
}
